package com.jushu.storbox.newfragment;

import java.util.List;
import java.util.Stack;

import android.app.ActionBar.LayoutParams;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.jushu.storbox.FileBrowserAllFileActivity;
import com.jushu.storbox.R;
import com.jushu.storbox.ShareDriveApplication;
import com.jushu.storbox.TargetFolderBrowserActivity;
import com.jushu.storbox.TeamFileSearchActivity;
import com.jushu.storbox.actions.NodeAction;
import com.jushu.storbox.actions.UploadAction;
import com.jushu.storbox.constant.ClientConfig;
import com.jushu.storbox.constant.ErrorConstant;
import com.jushu.storbox.constant.IntentConstant;
import com.jushu.storbox.constant.MessageCode;
import com.jushu.storbox.constant.UiConstant;
import com.jushu.storbox.entities.FileFolderInfo;
import com.jushu.storbox.handler.ClientExceptionRelateHandler;
import com.jushu.storbox.newfragment.argument.FileActionArgs;
import com.jushu.storbox.newfragment.argument.TeamListActionArgs;
import com.jushu.storbox.util.LogUtil;
import com.jushu.storbox.util.PublicTools;
import com.jushu.storbox.view.dialog.CreateFolderDialog;
import com.jushu.storbox.view.dialog.PopupMenuWindow;
import com.jushu.storbox.view.resolve.TeamFileListResolve;
import com.jushu.storbox.view.resolve.TeamListResolve;
import com.huawei.sharedrive.sdk.android.exception.ClientException;
import com.huawei.sharedrive.sdk.android.modelV2.response.FolderResponse;
import com.huawei.sharedrive.sdk.android.util.StringUtil;
import com.kennyc.view.MultiStateView;

public class TeamFragment extends AbsFrameFragment {

	private TeamListResolve teamListResolve;
	private TeamFileListResolve fileListResolve;

	private TitleViewHolder titleHolder = null;
	private ProgressDialog waitDialog;

	@Override
	protected int getTitleResourceId() {
		return R.layout.action_title_style_one;
	}

	@Override
	protected int getContentResourceId() {
		return R.layout.action_body_style_one;
	}

	@Override
	protected void startInitConpentData() {
		waitDialog = new ProgressDialog(getMainFrameActivity());
		waitDialog.setMessage(getMainFrameActivity().getResources().getString(R.string.loading));
	}

	@Override
	protected void onLoadTitleView(View titleView) {
		super.onLoadTitleView(titleView);
		titleHolder = new TitleViewHolder(titleView);
	}

	@Override
	protected void onLoadContentView(View contentView) {
		super.onLoadContentView(contentView);
		PullToRefreshListView targetView = (PullToRefreshListView) contentView.findViewById(R.id.file_action_content_list);
		teamListResolve = new TeamListResolve(getMainFrameActivity(), getArgumentBundle(), (MultiStateView) contentView.findViewById(R.id.multiStateView)) {
			@Override
			protected void updateCurrentFolder(String ownerId, String folderId, String folderName) {
				titleHolder.tvTitle.setText(folderName);
				
				FileActionArgs args = new FileActionArgs();
				args.setOwnerId(ownerId);
				args.setFolderId(folderId);
				args.setFolderName(folderName);
				titleHolder.enterFolderFromTop();
				fileListResolve.setFolderArgument(args);
				fileListResolve.binddingAdapter();
			}
		};

		FileActionArgs args = new FileActionArgs();
		fileListResolve = new TeamFileListResolve(getMainFrameActivity(), args, teamListResolve.getComponent()) {
			public void onMove(int index, FileFolderInfo info) {
				Intent intent = new Intent(context, TargetFolderBrowserActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString(IntentConstant.INTENT_TARGET_RESOURCE_OWNER, info.getOwnerId());
				bundle.putString(IntentConstant.INTENT_TITLE_NAME, "团队空间");
				bundle.putInt(IntentConstant.INTENT_SOURCE_RESOURCE_TYPE, info.getType());
				bundle.putInt(IntentConstant.INTENT_COMEFROM_REQUEST, IntentConstant.INTENT_REQUEST_MOVETEAM);//
				bundle.putSerializable(IntentConstant.INTENT_DATA_EXTENDS_1, info);
				intent.putExtra(IntentConstant.INTENT_SEARCH_TARGET_DATA, bundle);
				startActivityForResult(intent, IntentConstant.INTENT_REQUEST_SEARCH_TARGET);
			}

			public void onTransfer(int index, FileFolderInfo info) {
				Intent intent = new Intent(context, TargetFolderBrowserActivity.class);
				Bundle bundle = new Bundle();
				bundle.putInt(IntentConstant.INTENT_SOURCE_RESOURCE_TYPE, info.getType());
				bundle.putInt(IntentConstant.INTENT_COMEFROM_REQUEST, IntentConstant.INTENT_REQUEST_TRANSFERTEAM);//
				bundle.putString(IntentConstant.INTENT_TARGET_RESOURCE_OWNER, ShareDriveApplication.getInstance().getWnerID());
				bundle.putString(IntentConstant.INTENT_SOURCE_RESOURCE_ID, info.getId());
				bundle.putString(IntentConstant.INTENT_SOURCE_RESOURCE_OWNER, info.getOwnerId().toString());
				intent.putExtra(IntentConstant.INTENT_SEARCH_TARGET_DATA, bundle);
				startActivityForResult(intent, IntentConstant.INTENT_REQUEST_COPY_TARGET);
			}

			@Override
			protected void updateCurrentFolder(String ownerId, String folderId, String folderName) {
				titleHolder.tvTitle.setText(folderName);
				if (StringUtil.isBlank(ownerId) && StringUtil.isBlank(folderId)) {
					titleHolder.backToTopLayer();
					teamListResolve.binddingAdapter();
				} else {
					titleHolder.enterFolderFromTop();
				}
			}
		};

		teamListResolve.initComponent(targetView);
		fileListResolve.initComponent(targetView);
		
		teamListResolve.binddingAdapter();
	}

	public void doUpdateCurrentFolder(String ownerId, String folderId, String folderName) {
//		titleHolder.tvTitle.setText(folderName);
//		if (fileListResolve == null) {
//			FileActionArgs args = new FileActionArgs();
//			args.setOwnerId(ownerId);
//			args.setFolderId(folderId);
//			args.setFolderName(folderName);
//			fileListResolve = new TeamFileListResolve(getMainFrameActivity(), args, teamListResolve.getComponent()) {
//
//				public void onMove(int index, FileFolderInfo info) {
//					Intent intent = new Intent(context, TargetFolderBrowserActivity.class);
//					Bundle bundle = new Bundle();
//					bundle.putString(IntentConstant.INTENT_TARGET_RESOURCE_OWNER, info.getOwnerId());
//					bundle.putInt(IntentConstant.INTENT_SOURCE_RESOURCE_TYPE, info.getType());
//					bundle.putInt(IntentConstant.INTENT_COMEFROM_REQUEST, IntentConstant.INTENT_REQUEST_MOVETEAM);//
//					bundle.putSerializable(IntentConstant.INTENT_DATA_EXTENDS_1, info);
//					intent.putExtra(IntentConstant.INTENT_SEARCH_TARGET_DATA, bundle);
//					startActivityForResult(intent, IntentConstant.INTENT_REQUEST_SEARCH_TARGET);
//				}
//
//				public void onTransfer(int index, FileFolderInfo info) {
//					Intent intent = new Intent(context, TargetFolderBrowserActivity.class);
//					Bundle bundle = new Bundle();
//					bundle.putInt(IntentConstant.INTENT_SOURCE_RESOURCE_TYPE, info.getType());
//					bundle.putInt(IntentConstant.INTENT_COMEFROM_REQUEST, IntentConstant.INTENT_REQUEST_TRANSFERTEAM);//
//					bundle.putString(IntentConstant.INTENT_TARGET_RESOURCE_OWNER, ShareDriveApplication.getInstance().getWnerID());
//					bundle.putString(IntentConstant.INTENT_SOURCE_RESOURCE_ID, info.getId());
//					bundle.putString(IntentConstant.INTENT_SOURCE_RESOURCE_OWNER, info.getOwnerId().toString());
//					intent.putExtra(IntentConstant.INTENT_SEARCH_TARGET_DATA, bundle);
//					startActivityForResult(intent, IntentConstant.INTENT_REQUEST_COPY_TARGET);
//				}
//			};
//		}
//		if (ownerId == null && folderId == null) {
//			titleHolder.backToTopLayer();
//			teamListResolve.binddingAdapter();
//		} else if (fileListResolve.getFolderStack().isEmpty() && Constant.ROOT_FOLDER_ID.equals(folderId)) {
//			FileActionArgs args = new FileActionArgs();
//			args.setOwnerId(ownerId);
//			args.setFolderId(folderId);
//			args.setFolderName(folderName);
//			titleHolder.enterFolderFromTop();
//			fileListResolve.setFolderArgument(args);
//			fileListResolve.binddingAdapter();
//		}
		LogUtil.e("doUpdateCurrentFolder", "NO Use agine...");
	}

	@Override
	public TeamListActionArgs getArgumentBundle() {
		TeamListActionArgs tempArgument = (TeamListActionArgs) super.getArgumentBundle();
		if (tempArgument == null) {
			tempArgument = new TeamListActionArgs();
			setArgument(tempArgument);
		}
		return tempArgument;
	}

	@Override
	protected boolean touchRoot() {
		if (fileListResolve == null) {
			return true;
		}
		if (fileListResolve.getFolderStack().isEmpty()) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	protected void onBackPressed() {
		fileListResolve.openParentFolder();
	}

	class TitleViewHolder {
		View titleContainer;
		View rlReturn;
		View ivReturn;
		TextView tvTitle;
		LinearLayout operatorLayout;
		View imgSearch;
		View imgUpload;
		View imgMore;

		public TitleViewHolder(View container) {
			titleContainer = container;
			ivReturn = titleContainer.findViewById(R.id.file_action_title_returnIcon);
			tvTitle = (TextView) titleContainer.findViewById(R.id.file_action_title_folderId);
			tvTitle.setText(R.string.team_space);
			rlReturn = titleContainer.findViewById(R.id.file_action_title_return_Rl);
			rlReturn.setOnClickListener(new OnClickListener() {
				public void onClick(View arg0) {
					if (!handleBackPressed()) {
						return;
					}
				}
			});
			operatorLayout = (LinearLayout) titleContainer.findViewById(R.id.teamspace_title_file_oper);
			operatorLayout.setVisibility(View.INVISIBLE);
			imgSearch = titleContainer.findViewById(R.id.file_action_title_search);
			imgSearch.setOnClickListener(new OnClickListener() {
				public void onClick(View arg0) {
					Intent intent = new Intent(getMainFrameActivity(), TeamFileSearchActivity.class);
					FileActionArgs tempArg = fileListResolve.getFolderArgument();
					if (tempArg != null) {
						String folderName = tempArg.getFolderName();
						String ownerId = tempArg.getOwnerId();
						intent.putExtra(IntentConstant.INTENT_DATA_EXTENDS_1, ownerId);
						intent.putExtra(IntentConstant.INTENT_DATA_EXTENDS_2, folderName);
						startActivityForResult(intent, IntentConstant.INTENT_REQUEST_SEARCHFILE);
					}
				}
			});
			imgUpload = titleContainer.findViewById(R.id.file_action_title_upload);
			imgUpload.setOnClickListener(new OnClickListener() {
				public void onClick(View arg0) {
					Intent dataAllFile = new Intent();
					dataAllFile.setClass(getMainFrameActivity(), FileBrowserAllFileActivity.class);
					startActivityForResult(dataAllFile, MessageCode.UPLOAD_SELECT_FILE_REQCODE);
				}
			});
			imgMore = titleContainer.findViewById(R.id.file_action_title_moreOperation);
			imgMore.setOnClickListener(new OnClickListener() {
				public void onClick(View view) {
					PopupMenuWindow popMenuWindow = new PopupMenuWindow(getActivity(), (int) getActivity().getResources().getDimension(
							R.dimen.item_popup_more_window_width_l), LayoutParams.WRAP_CONTENT, R.layout.adapter_view_title_more_item) {
						public void onInflaterFinished(View contentView) {
							View createFolder = contentView.findViewById(R.id.adapter_view_title_menu_createFolder);
							createFolder.setOnClickListener(new OnClickListener() {
								public void onClick(View arg0) {
									dismiss();
									new CreateFolderDialog().createFolder(getMainFrameActivity(), fileListResolve.getFolderArgument().getOwnerId(),
											fileListResolve.getFolderArgument().getFolderId(), msgHandler, waitDialog);
								}
							});
							View mutilSelect = contentView.findViewById(R.id.adapter_view_title_menu_mutilSelect);
							mutilSelect.setVisibility(View.GONE);
							contentView.findViewById(R.id.mutilSelect_line_1).setVisibility(View.GONE);
							contentView.findViewById(R.id.mutilSelect_line_2).setVisibility(View.GONE);
							View sortByName = contentView.findViewById(R.id.adapter_view_title_menu_sortByName);
							// sortByName.setVisibility(View.GONE);
							sortByName.setOnClickListener(new OnClickListener() {
								public void onClick(View arg0) {
									dismiss();
									fileListResolve.sortByName(getCurrentSorttype(UiConstant.TEMA_SUB_FILENAME_SORT));
								}
							});
							View sortByTime = contentView.findViewById(R.id.adapter_view_title_menu_sortByTime);
							// sortByTime.setVisibility(View.GONE);
							sortByTime.setOnClickListener(new OnClickListener() {
								public void onClick(View arg0) {
									dismiss();
									fileListResolve.sortByTime(getCurrentSorttype(UiConstant.TEMA_SUB_TIME_SORT));
								}
							});
							View sortBySize = contentView.findViewById(R.id.adapter_view_title_menu_sortBySize);
							sortBySize.setOnClickListener(new OnClickListener() {
								@Override
								public void onClick(View v) {
									dismiss();
									fileListResolve.sortBySize(getCurrentSorttype(UiConstant.TEMA_SUB_SIZE_SORT));
								}

							});
						}
					};
					int[] location = new int[2];
					view.getLocationOnScreen(location);

					// -5 -- background border is 5dp
					popMenuWindow.showAtLocation(titleContainer, Gravity.NO_GRAVITY, location[0] - popMenuWindow.getWidth() + view.getWidth(), location[1]
							+ titleContainer.getHeight() - PublicTools.dipTopx(getActivity(), 5));
				}
			});
		}

		public void backToTopLayer() {
			operatorLayout.setVisibility(View.INVISIBLE);
			ivReturn.setVisibility(View.GONE);
		}

		public void enterFolderFromTop() {
			operatorLayout.setVisibility(View.VISIBLE);
			ivReturn.setVisibility(View.VISIBLE);
		}
	}

	int getCurrentSorttype(String sortType) {
		SharedPreferences sharepreferences = getActivity().getSharedPreferences(ClientConfig.settings, Context.MODE_APPEND);
		if (sortType.equals(UiConstant.TEMA_SUB_TIME_SORT)) {
			return sharepreferences.getInt(UiConstant.TEMA_SUB_TIME_SORT, UiConstant.TEMA_SUB_SORT_BY_TIME) ^ 0x1000;
		} else if (sortType.equals(UiConstant.TEMA_SUB_SIZE_SORT)) {
			return sharepreferences.getInt(UiConstant.TEMA_SUB_SIZE_SORT, UiConstant.TEMA_SUB_SORT_BY_SIZE) ^ 0x1000;
		} else /* if(sortType.equals(UiConstant.TEMA_SUB_FILENAME_SORT)) */{
			return sharepreferences.getInt(UiConstant.TEMA_SUB_FILENAME_SORT, UiConstant.TEMA_SUB_SORT_BY_FILENAME) ^ 0x1000;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case MessageCode.UPLOAD_SELECT_FILE_REQCODE:
			if (resultCode == MessageCode.UPLOAD_SELECT_FILE_RESULTCODE) {
				Bundle bundle = data.getBundleExtra("result");
				List<String> resultUrlList = bundle.getStringArrayList("resultUIL");
				new UploadAction().uploadFile(getMainFrameActivity(), fileListResolve.getFolderArgument().getOwnerId(), fileListResolve.getFolderArgument()
						.getFolderId(), resultUrlList, msgHandler);
			}
			break;
		case IntentConstant.INTENT_REQUEST_SEARCH_TARGET:
			switch (resultCode) {
			case MessageCode.MOVE_SUCCESS: // 团队空间移动成功
				Bundle bundle = data.getBundleExtra(IntentConstant.INTENT_SEARCH_TARGET_DATA);
				FileFolderInfo info = (FileFolderInfo) bundle.getSerializable(IntentConstant.INTENT_DATA_EXTENDS_1);
				fileListResolve.getAdapter().removeData(info);
				Toast.makeText(getActivity(), R.string.action_team_move_success, Toast.LENGTH_SHORT).show();

				break;
			case UiConstant.NODE_ACTION_MOVE_CANCEL: // 团队空间取消自动重命名
				// Toast.makeText(getActivity(),
				// R.string.action_file_promit_move_source_success_except_duplication_of_name,
				// Toast.LENGTH_SHORT).show();
				break;
			}
			break;
		case IntentConstant.INTENT_REQUEST_COPY_TARGET:
			switch (resultCode) {
			case MessageCode.TRANSFER_TO_MY_FILE_SUCCESS: // 团队空间转存到我的云盘成功
				Toast.makeText(getActivity(), R.string.operate_success, Toast.LENGTH_SHORT).show();
				break;

			case UiConstant.SHARE_ACTION_SAVE_CANCEL: // 团队空间转存到我的云盘取消自动重命名
				// Toast.makeText(getActivity(),
				// R.string.action_share_save_to_my_cloud_cancel,
				// Toast.LENGTH_SHORT).show();
				break;
			}
			break;
		case IntentConstant.INTENT_REQUEST_SEARCHFILE:
			switch(resultCode){
				case IntentConstant.INTENT_RESULT_SEARCHFILE_NULL:
					break;
				case IntentConstant.INTENT_RESULT_SEARCHFILE_VALUE:
					 FileFolderInfo info = (FileFolderInfo) data.getSerializableExtra(IntentConstant.INTENT_SEARCH_FILE_DATA);
					 new NodeAction().getNodePath(getActivity(), msgHandler, info);
					break;
			}
			break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	ClientExceptionRelateHandler msgHandler = new ClientExceptionRelateHandler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MessageCode.UPLOAD_FAIL:
				if (msg.obj instanceof ClientException) {
					ClientException ex = (ClientException) msg.obj;
					if (ex.getStatusCode() == ERROR_CODE_404_NO_RESOURCE && ErrorConstant.UPLOAD_CALLBACK_FAIL.equals(ex.getCode())) {
						Toast.makeText(getMainFrameActivity(), getMainFrameActivity().getResources().getString(R.string.teamspace_upload_fail),
								Toast.LENGTH_SHORT).show();
						// fileListResolve.getFolderStack().clear();
						// titleHolder.backToTopLayer();
						// teamListResolve.binddingAdapter();
						// teamListResolve.loadDataList();
					}
				} else {
					Toast.makeText(getMainFrameActivity(), getMainFrameActivity().getResources().getString(R.string.fileListadapter_upload_failed),
							Toast.LENGTH_SHORT).show();
				}
				break;
			case MessageCode.UPLOAD_SUCCESS:
				FileFolderInfo fileInfo = (FileFolderInfo) msg.obj;
				Toast.makeText(getMainFrameActivity(),
						"[" + fileInfo.getName().toString() + "]" + getMainFrameActivity().getResources().getString(R.string.fileListadapter_upload_success),
						Toast.LENGTH_SHORT).show();
				fileListResolve.addData(fileInfo);
				break;
			case MessageCode.CREATE_FOLDER_SUCCESS:
				waitDialog.dismiss();
				fileListResolve.addData(0, (FileFolderInfo) msg.obj);
				break;
			case UiConstant.NODE_ACTION_GET_PATH:
				Bundle bundle = msg.getData();
				FileFolderInfo folderinfo = (FileFolderInfo) bundle.getSerializable(IntentConstant.INTENT_DATA_EXTENDS_1);
				List<FolderResponse> values = (List<FolderResponse>) msg.obj;
				Stack<FileActionArgs> fileStack = fileListResolve.getFolderStack();
				FileActionArgs rootTema = fileStack.get(0); 
				fileStack.clear();
				fileStack.push(rootTema);
				fileStack.push(rootTema);	//适配原来的栈逻辑
				for(int i=values.size()-1; i>=0; i--){
					FolderResponse value = values.get(i);
					FileActionArgs object = new FileActionArgs();
					object.setFolderId(value.getId());
					object.setFolderName(value.getName());
					object.setOwnerId(value.getOwnerBy());
					fileStack.push(object);
				}
				fileListResolve.setFolderArgument(fileStack.pop());
				fileListResolve.openFolderWithWait(0, folderinfo);
				break;
			default:
				if (waitDialog.isShowing()) {
					waitDialog.dismiss();
				}
				super.handleMessage(msg);
			}
		}

		@Override
		public Context getContext() {
			return getActivity();
		}
	};

}
